/*
 * 项目名称:platform-plus
 * 类名称:CustomerServiceImpl.java
 * 包名称:com.platform.modules.customer.service.impl
 *
 * 修改履历:
 *     日期                       修正者        主要内容
 *     2020-10-10 14:34:32        klwu     初版做成
 *
 * Copyright (c) 2019-2019 klwu
 */
package com.platform.modules.custmoer.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.Query;
import com.platform.common.utils.StringUtils;
import com.platform.modules.custmoer.dao.CustomerDao;
import com.platform.modules.custmoer.dto.*;
import com.platform.modules.custmoer.entity.CustRecordEntity;
import com.platform.modules.custmoer.entity.CustomerEntity;
import com.platform.modules.custmoer.entity.StaffEntity;
import com.platform.modules.custmoer.service.CustRecordService;
import com.platform.modules.custmoer.service.CustomerService;
import com.platform.modules.custmoer.service.StaffService;
import com.platform.modules.utils.LocationUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * Service实现类
 *
 * @author klwu
 * @date 2020-10-10 14:34:32
 */
@Service("customerService")
public class CustomerServiceImpl extends ServiceImpl<CustomerDao, CustomerEntity> implements CustomerService {

    @Autowired
    private CustRecordService custRecordService;
    @Autowired
    private StaffService staffService;

    @Override
    public List<CustomerEntity> queryAll(Map<String, Object> params) {
        return baseMapper.queryAll(params);
    }

    @Override
    public Page queryPage(Map<String, Object> params) {
        //排序
        params.put("sidx", "T.CREATE_TIME");
        params.put("asc", false);
        Page<CustomerEntity> page = new Query<CustomerEntity>(params).getPage();
        List<CustomerEntity> customerEntityList = baseMapper.selectCustomerPage(page, params);
        customerEntityList.forEach(new Consumer<CustomerEntity>() {
            @Override
            public void accept(CustomerEntity customerEntity) {
                if(!StringUtils.isEmpty(customerEntity.getStaffId())){
                    customerEntity.setStaffName(staffService.getById(customerEntity.getStaffId()).getName());
                }
                if("0".equals(customerEntity.getStatus())){
                    customerEntity.setStatusStr("低意向");
                }else if("1".equals(customerEntity.getStatus())){
                    customerEntity.setStatusStr("中意向");
                }else if("2".equals(customerEntity.getStatus())){
                    customerEntity.setStatusStr("高意向");
                }
            }
        });
        return page.setRecords(customerEntityList);
    }

    public Page queryHomeListPage(Map<String, Object> params) {
        Page<HomeDataDto> page1 = new Page<HomeDataDto>();
        page1.setTotal(1);
        HomeDataDto h = new HomeDataDto();
        h.setProvince("广东");
        h.setOrderNum(1005);
        h.setCustNum(20000);
        h.setVistorNum(25000);
        h.setStaffNum(10001);
        List homeList = Arrays.asList(h);
        return page1.setRecords(homeList);
    }

    @Override
    public boolean add(CustomerEntity customer) {
        return this.save(customer);
    }

    @Override
    public boolean update(CustomerEntity customer) {
        if("1".equals(customer.getType())){
            customer.setStaffId("");
        }
        if(customer.getAddress() != null && customer.getProvince() != null && customer.getCity() != null){
            String address = customer.getProvince() + customer.getCity() + customer.getTown() + customer.getAddress();
            String lgt = "";
            String lat = "";
            try {
                LocationUtil locationUtil = new LocationUtil();
                Object[] coordinate = locationUtil.getCoordinate(address);
                lgt = (String) coordinate[0];
                lat = (String) coordinate[1];
            }catch (Exception e){
                e.printStackTrace();
            }
            customer.setLat(lat);
            customer.setLgt(lgt);
        }
        return baseMapper.updateCustomer(customer);
    }

    @Override
    public boolean delete(String id) {
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(String[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public List<MyCustomersDto> queryMyCustomers(Map<String, Object> map) {
        List<CustomerEntity> customerEntityList = queryAll(map);
        List<MyCustomersDto> collect = customerEntityList.stream().map(customerEntity -> {
            MyCustomersDto myCustomersDto = new MyCustomersDto();
            BeanUtils.copyProperties(customerEntity,myCustomersDto);
            if(!StringUtils.isEmpty(customerEntity.getStaffId())){
                myCustomersDto.setStaffName(staffService.getById(customerEntity.getStaffId()).getName());
            }
            //myCustomersDto.setCreateTime(DateUtils.getDate(customerEntity.getCreateTime()));
            return myCustomersDto;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public CustomerDetailDto constructionDetail(CustomerEntity customerEntity) {
        CustomerDetailDto customerDetailDto = new CustomerDetailDto();
        Map<String,Object> recordMap = new HashMap<>();
        recordMap.put("custId",customerEntity.getId());
        List<CustRecordEntity> records = custRecordService.queryAll(recordMap);

        List<CustomerRecordDto> collect = records.stream().map(record -> {
            CustomerRecordDto customerRecordDto = new CustomerRecordDto();
            BeanUtils.copyProperties(record, customerRecordDto);
            return customerRecordDto;
        }).collect(Collectors.toList());

        BeanUtils.copyProperties(customerEntity, customerDetailDto);
        customerDetailDto.setRecordDtoList(collect);

        return customerDetailDto;
    }

    @Override
    public List<MyCustomersDto> selectlastThreeDay(Map<String, Object> params) {
        List<CustomerEntity> customerEntityList = baseMapper.selectlastThreeDay(params);
        List<MyCustomersDto> collect = customerEntityList.stream().map(customerEntity -> {
            MyCustomersDto myCustomersDto = new MyCustomersDto();
            BeanUtils.copyProperties(customerEntity,myCustomersDto);
            if(!StringUtils.isEmpty(customerEntity.getStaffId())){
                myCustomersDto.setStaffName(staffService.getById(customerEntity.getStaffId()).getName());
            }
            return myCustomersDto;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public boolean updateCustomer(CustomerEntity customerEntity) {
        return baseMapper.updateCustomer(customerEntity);
    }

    @Override
    public List<CustmoerMonthCountEntity> custCount(Map<String, Object> params) {
        return baseMapper.custCount(params);
    }

    /**
     * 获取过去7天内的日期数组
     * @param intervals      intervals天内
     * @return              日期数组
     */
    public ArrayList<String> getDays(int intervals) {
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = intervals -1; i >= 0; i--) {
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }
    /**
     * 获取过去第几天的日期
     * @param past
     * @return
     */
    public String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    @Override
    public List<String> getLastDays(Map<String, Object> params) {
        return getDays(7);
    }

    @Override
    public void handleExcel(Map<String, List<String[]>> itemsMap) {
        for(Map.Entry<String, List<String[]>> entry : itemsMap.entrySet()){
            List<String[]> customers = entry.getValue();
            if(customers != null && customers.size() > 0){
                for(String[] cloumn : customers){
                    String staffName = cloumn[0]; // 业务员姓名
                    String custName = cloumn[1]; // 客户姓名
                    String custPhone = cloumn[2]; // 客户电话
                    String custAddress = cloumn[3]; // 客户地址
                    String staffPhone = cloumn[4]; // 业务员电话
                    try {
                        HandleStaffPhone(staffPhone,staffName,custName,custPhone,custAddress);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 如果售后电话这个帐号不存在，就新建一个帐号，再把客户信息添加进去
     * @param phone
     */
    public void HandleStaffPhone(String phone,String name,String custName,String custPhone,String address) throws IOException, NoSuchAlgorithmException {
        LocationUtil getLatAndLngByBaidu = new LocationUtil();
        Map params = new HashMap();
        params.put("phone",phone);
        List<StaffEntity>list = staffService.queryAll(params);
        if(list != null && list.size() > 0){
            // 存在
            StaffEntity staffEntity = list.get(0);
            CustomerEntity customerEntity = new CustomerEntity();
            customerEntity.setCustName(custName);
            customerEntity.setPhone(custPhone);
            customerEntity.setStaffId(staffEntity.getId());
            Object[] coordinate = getLatAndLngByBaidu.getCoordinate(address);
            if(coordinate != null && coordinate.length == 2){
                String lgt = (String) coordinate[0];
                String lat = (String) coordinate[1];
                customerEntity.setLgt(lgt);
                customerEntity.setLat(lat);
            }
            customerEntity.setCreateTime(new Date());
            customerEntity.setAddress(address);
            this.save(customerEntity);
        }else {
            StaffEntity staffEntity = new StaffEntity();
            CustomerEntity customerEntity = new CustomerEntity();
            staffEntity.setPhone(phone);
            staffEntity.setName(name);
            staffEntity.setCreateTime(new Date());
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update("888888".getBytes());// 初始密码
            byte[] result = md.digest(); // 16 21218cca77804d2ba1922c33e0151105
            String password = new BigInteger(1, result).toString(16);
            staffEntity.setPassword(password);
            staffService.add(staffEntity);

            String staffId = staffEntity.getId();
            customerEntity.setCustName(custName);
            customerEntity.setPhone(custPhone);
            customerEntity.setStaffId(staffId);
            Object[] coordinate = getLatAndLngByBaidu.getCoordinate(address);
            if(coordinate != null && coordinate.length == 2){
                String lgt = (String) coordinate[0];
                String lat = (String) coordinate[1];
                customerEntity.setLgt(lgt);
                customerEntity.setLat(lat);
            }
            customerEntity.setCreateTime(new Date());
            customerEntity.setAddress(address);
            this.save(customerEntity);
        }
    }

    public double custTotal(){
        return baseMapper.custTotal();
    }

    public double precustTotal(){
        return baseMapper.precustTotal();
    }

    @Override
    public boolean updateCustomerByApp(CustomerEntity customerEntity) {
        return baseMapper.updateCustomer(customerEntity);
    }

}
